import { useContext, useState, useEffect } from "react";
import { ConnContext } from "../contexts/Conn";

const useRetrieveData = (state, initData) => {

  const {send, cast, release} = useContext(ConnContext);

  const [data, setData] = useState(initData);

  const updateData = (data) => {
    console.log('updateData');
    setData(data);
  }

  useEffect(() => {

    console.log('retrieving data');

    const {query: {event, content={}}={}} = state;

    if (event) {
      cast(event, updateData);
      send(event, content);
    }

    return () => {
      release(event);
    }
  }, [state]);
  
  return data;
}

export default useRetrieveData;